$(document).ready(function() {
	// create sidebar and attach to menu open
	$('.ui.sidebar').sidebar('setting', 'mobileTransition', 'overlay').sidebar('attach events', '.toc.item');

	$('#fullpage').fullpage({
		//Navigation
		menu: '#menu',
		lockAnchors: false,
		anchors:['home', 'honor', 'motto', 'picture', 'video', 'social'],
		navigation: false,
		navigationPosition: 'right',
		navigationTooltips: ['firstSlide', 'secondSlide'],
		showActiveTooltip: false,
		slidesNavigation: true,
		slidesNavPosition: 'bottom',

		//Scrolling
		css3: true,
		scrollingSpeed: 444,
		autoScrolling: true,
		fitToSection: true,
		fitToSectionDelay: 1000,
		scrollBar: false,
		easing: 'easeInOutCubic',
		easingcss3: 'ease',
		loopBottom: false,
		loopTop: false,
		loopHorizontal: true,
		continuousVertical: false,
		normalScrollElements: '#element1, .element2',
		scrollOverflow: false,
		scrollOverflowOptions: null,
		touchSensitivity: 15,
		normalScrollElementTouchThreshold: 5,

		//Accessibility
		keyboardScrolling: true,
		animateAnchor: true,
		recordHistory: true,

		//Design
		controlArrows: true,
		verticalCentered: [false, true, true, true, true, true],
		sectionsColor : ['#1B1C1D', '#fff', '#000', '#000', '#fff', '#fff'],
		paddingTop: '0',
		paddingBottom: '0',
		fixedElements: '#header, .footer',
		responsiveWidth: 0,
		responsiveHeight: 0,

		//Custom selectors
		sectionSelector: '.section',
		slideSelector: '.slide',

		//events
		onLeave: function(index, nextIndex, direction){},
		afterLoad: function(anchorLink, index){},
		afterRender: function(){},
		afterResize: function(){},
		afterSlideLoad: function(anchorLink, index, slideAnchor, slideIndex){},
		onSlideLeave: function(anchorLink, index, slideIndex, direction, nextSlideIndex){}
	});
	$.fn.fullpage.setRecordHistory(false);
	$('.special.cards .image').dimmer({
		on: 'click'
	});

	var networkDisconnect = false;
	var background = false;
	var myMedia = null;
	var myMediaRelease = false;
	var myPlayer=videojs("really-cool-video");
	var down = true;
	var page_anchors = ['home', 'motto', 'honor', 'picture', 'video', 'social'];
	var imgUrl = ['http://hbimg.b0.upaiyun.com/899fb128d58afba01c008432999033b4de1de8f4132c1-Ub4GjC_fw658',
	'http://hbimg.b0.upaiyun.com/dd0f16841bccc287d343035f898c569fca7f45eb51201-nNuj5s_fw658',
	'http://hbimg.b0.upaiyun.com/d0d06ed7266aaf967918569186007a3f3532772b54ae8-i4Olsl_fw658',
	'http://hbimg.b0.upaiyun.com/3df8a991dc268bae7a0887e52408d4a8e48d4f095f28e-KasAal_fw658'];

	// event listener
	document.addEventListener("deviceready", playAudio, false);
	document.addEventListener("deviceready", shakeScreen, false);
	document.addEventListener("deviceready", imageTap, false);
	document.addEventListener("deviceready", leftMenu, false);
	document.addEventListener("deviceready", exitMyApp, false);
	document.addEventListener("deviceready", onPause, false);
	document.addEventListener("deviceready", onResume, false);
	document.addEventListener("deviceready", network, false);
	document.addEventListener("deviceready", checkConnection, false);
	document.addEventListener("deviceready", videoCheck, false);
	document.addEventListener("deviceready", weiboInit, false);

	function weiboInit()
	{
		// 初始化微博插件
		window.weibo.init('646740500','http://www.sina.com');

		// 按钮事件绑定
		var parentElement = document.getElementById('wrapper');
		parentElement.querySelector('#check-install').addEventListener('click', checkInstall, false);
		parentElement.querySelector('#sso-login').addEventListener('click', ssoLogin, false);
		parentElement.querySelector('#share-text').addEventListener('click', shareText, false);
	}

	function checkInstall()
	{
		window.weibo.isInstalled(function(status){
			var text = status ? '已安装微博客户端！' : '未安装微博客户端！';
			alert(text);
		})
	}

	function ssoLogin()
	{
		window.weibo.login(function(res){
			alert('授权成功！\n uid: ' + res.uid + '\n access_token: ' + res.token + '\n refresh_token: ' + res.refresh_token);
		},function(err){
			if(err === 'cancel') {
				alert('用户取消授权')
			} else {
				alert('授权失败');
			}
		})
	}

	function shareText()
	{
		window.weibo.isInstalled(function(status){
			if(status){
				window.weibo.share({
					type: 'image',
					data: imgUrl[0],
					text: 'test my plugin'
				},function(res){
					alert('发送成功');
				},function(res){
					if(res === 'cancel') {
						alert('用户取消分享')
					} else {
						alert('发送失败');
					}
				});
			}else{
				alert('请先安装微博客户端！');
			}
		})
	}


	function network()
	{
		document.addEventListener("offline", onOffline, false);
		document.addEventListener("online", onOnline, false);
	}

	function onOnline()
	{
		if (networkDisconnect) {
			window.location.reload(true);
			window.plugins.toast.showShortTop('网络已连接');
			networkDisconnect = false;
		}
	}

	function onOffline()
	{
		networkDisconnect = true;
		window.plugins.toast.showShortTop('网络断开，请检查网络连接');
	}

	function checkConnection()
	{
		setInterval(function() {
			if (navigator.connection.type === Connection.NONE)
				window.plugins.toast.showLongTop('网络不可用，请检查网络连接');
		}, 25 * 1000);
	}

	function exitMyApp()
	{
		document.addEventListener("backbutton", function(e) {
			e.preventDefault();
			navigator.notification.confirm(
					"确定退出？", function(button) {
						if (button == 1) {
							if (!myPlayer.paused()) myPlayer.pause();
							myMediaRelease = true;
							myMedia = null;
							navigator.app.exitApp();
						}
					}
					, "退出应用"
					, "确定, 取消"
					);
		}, false);
	}

	function leftMenu()
	{
		var full = document.getElementById('fullpage');
		var mc = new Hammer(full);
		var startDragAtBorder = false;
		$(document).on('touchstart', function(e) {
			var xPos = e.originalEvent.touches[0].pageX;
			console.info(xPos);
			if (xPos < 5) {
				startDragAtBorder = true;
			} else {
				startDragAtBorder = false;
			}
		});
		mc.on('swiperight', function() {
			if (startDragAtBorder) {
				$.fn.fullpage.setAllowScrolling(false, 'left');
				$('.ui.sidebar').sidebar('setting', 'mobileTransition', 'overlay').sidebar('toggle');
			} else {
				$.fn.fullpage.moveSlideLeft();
			}
		});
		$.fn.fullpage.setAllowScrolling(true, 'left');
	}

	function imageTap()
	{
		var myElement1 = document.getElementById('myImg1');
		var mc1 = new Hammer(myElement1);
		mc1.on('tap', function() {
			var ref = window.open(imgUrl[0], '_blank', 'hidden=yes,enableviewportscale=yes');
			ref.show();
		});
		var myElement2 = document.getElementById('myImg2');
		var mc2 = new Hammer(myElement2);
		mc2.on('tap', function() {
			var ref = window.open(imgUrl[1], '_blank', 'hidden=yes,enableviewportscale=yes');
			ref.show();
		});
		var myElement3 = document.getElementById('myImg3');
		var mc3 = new Hammer(myElement3);
		mc3.on('tap', function() {
			var ref = window.open(imgUrl[2], '_blank', 'hidden=yes,enableviewportscale=yes');
			ref.show();
		});
		var myElement4 = document.getElementById('myImg4');
		var mc4 = new Hammer(myElement4);
		mc4.on('tap', function() {
			var ref = window.open(imgUrl[3], '_blank', 'hidden=yes,enableviewportscale=yes');
			ref.show();
		});
	}

	function get_curpos()
	{
		var hash = window.location.hash.substring(1);
		var curpos = page_anchors.findIndex(function(element, index, array) {
			return element === hash;
		});
		if (curpos === -1) curpos = 0;
		return curpos;
	}

	function shakeScreen() {
		var onShake = function() {
			var curpos = get_curpos();
			if (down) {
				if (curpos === 5) {
					curpos--;
					down = false;
				} else curpos++;
			} else {
				if (curpos === 0) {
					curpos++;
					down = true;
				} else curpos--;
			}
			top.location = "#" + page_anchors[curpos];
		};
		shake.startWatch(onShake, 20);
	}

	// background music
	function playAudio() {
		if (!myMedia) {
			var src = get_media_url("assets/csgo.mp3");
			var loop = function (status) {
				if (!myMediaRelease && status === Media.MEDIA_STOPPED && myPlayer.paused()) {
					myMedia.play();
				}
			};
			myMedia = new Media(
					src,
					function() {
						console.log("playAudio Success");
					},
					function(error) {
						console.log("playAudio Error: " + error.code);
					},
					loop);
		}
		myMedia.play();
	}

	// FIXME when app go to background and call video pause first
	function videoCheck() {
		$('video').on('play', function() {
			myMedia.pause();
		});
		$('video').on('pause', function() {
			setTimeout(function() {
				if (!background) myMedia.play();
			}, 1000);
		});
	}

	function onPause() {
		document.addEventListener("pause", function() {
			background = true;
			myPlayer.pause();
			myMedia.pause();
		}, false);
	}

	function onResume() {
		document.addEventListener("resume", function() {
			window.location.reload(true);
			location.href = "#" + page_anchors[get_curpos()];
			background = false;
		}, false);
	}
});

function get_media_url(res)
{
	if (device.platform === "Android") return cordova.file.applicationDirectory + "www/" + res;
	return res;
};

